import { token } from '@/config/env';
import md5 from '@/utils/md5';

function sign(data) {
	const appId = '1113002';
	const appSecret = 'ddba481c-ce6e-5db9-ea94-4bf980021bbc';
	data.timeStamp = parseInt(new Date().getTime() / 1000);

	let arr = [];

	for (let i in data) {
		if (data[i] === undefined || data[i] == null) {
			continue;
		}

		arr.push(`${i}=${decodeURIComponent(data[i])}`);
	}

	arr.push(`appSecret=${appSecret}`);

	return md5(arr.sort().join('&'));
}

let lock = false;
function request(options) {
	const { isLoading, isSign } = options || {};

	if (!options.data) {
		options.data = {};
	}

	options.data.app = 'hf';

	// if (isLoading) {
	// 	uni.showLoading({
	// 		title: '加载中',
	// 		mask: true
	// 	});
	// }

	if (isSign) {
		options.data.sign = sign(options.data);
	}
	return new Promise((resolve, reject) => {
		uni.request({
			...options,

			header: {
				r: Date.parse(new Date()),
				Authorization: token || uni.getStorageSync('token')
			},

			success: res => {
				const { code, data, message } = res.data;

				switch (code) {
					case 1000:
						resolve(data);
						break;
					case 1001:
						reject(res.data);
						if (!lock) {
							lock = true;
							if (message === '登录失效，请重新登录~') {
								uni.showToast({
									title: message,
									icon: 'none'
								})
								uni.redirectTo({
									url: '/pages/common/login',
									success() {
										lock = false;
									}
								});
							}
						}

						break;
					default:
						reject(res.data);
				}

				resolve(data);
			},

			fail: err => {
				reject(err);
			},

			complete: () => {
				if (isLoading) {
					uni.hideLoading();
				}
			}
		});
	});
}

export { request };
